package com.proxy.autoclick.clicker.service;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.proxy.autoclick.checker.http.proxy.ClientExecuteProxy;
import com.proxy.autoclick.checker.http.proxy.ClientExecuteProxyGoTarget;
import com.proxy.autoclick.checker.http.proxy.ClientExecuteProxySearchGoogleHost;
import com.proxy.autoclick.clicker.dao.ClickerDao;
import com.proxy.autoclick.clicker.valueobject.KeywordAddress;
import com.proxy.autoclick.clicker.valueobject.SearchResultItem;
import com.proxy.autoclick.common.util.SpringBeanUtil;
import com.proxy.autoclick.common.valueobject.Proxy;
import com.proxy.autoclick.common.valueobject.ValidProxyQueue;
import com.proxy.autoclick.ui.layout.MainFrame;

public class ClickerService {
	
	private static final Logger LOGGER = Logger.getLogger(ClickerService.class);
	
	private ClickerDao clickerDao;
	private MainFrame mainFrame;
	private KeywordAddress keywordAddress;
	private HttpClient httpclient;
	private ValidProxyQueue validProxyQueue;
	private Proxy validProxy = null;
	private ClientExecuteProxy clientExecuteProxyGoogle = null;
	
	public ClickerService(KeywordAddress keywordAddress,HttpClient httpclient)
	{
		this.keywordAddress = keywordAddress;
		this.httpclient = httpclient;
//		this.myProxyList = myProxyList;
		clickerDao = (ClickerDao) SpringBeanUtil.getSpringBean("clickerDao");
		mainFrame  = (MainFrame)  SpringBeanUtil.getSpringBean("mainFrame");
		validProxyQueue  = (ValidProxyQueue)  SpringBeanUtil.getSpringBean("validProxyQueue");
	}
	
	public void startCheckAndClick() throws Exception
	{
		
		List<Document> documentList = this.getDocumentList();
		
		List<SearchResultItem> searchResultItemList = transformToSearchItemList(documentList);
		this.clickMatchedItem(searchResultItemList);
	}
	/**
	 * Generate a list(page 1-page 10) of query google result
	 * @param validProxy
	 * @return
	 * @throws Exception
	 */
	private List<Document> getDocumentList() throws Exception
	{
		List<Document> documentList = new ArrayList<Document>();
		
//		int proxyIndex = RandomNumUtil.getNumBetweenRange(0, myProxyList.size()-1);
		/*mainFrame.setTextAreaText(String.format("Checking query %s %s with Google", 
									keywordAddress.getKeyword(), 
									keywordAddress.getAddress()));*/
		mainFrame.setTextAreaText(String.format("Waitting proxy to check query %s %s with Google on page %s", 
				keywordAddress.getKeyword(), 
				keywordAddress.getAddress(),
				1));
		validProxy = validProxyQueue.take();
		mainFrame.setTextAreaText(String.format("Get a valid proxy %s and checking query %s %s " +
				"with Google on page %s", 
					validProxy.getProxy(),
					keywordAddress.getKeyword(), 
					keywordAddress.getAddress(),
					1));
		for(int i = 0; i < 10; i ++)
		{
			clientExecuteProxyGoogle = new ClientExecuteProxySearchGoogleHost
											(httpclient,validProxy,keywordAddress, i*10);
			Document document = clientExecuteProxyGoogle.execue();
			if(document == null)
			{
				while(true)
				{
					mainFrame.setTextAreaText(String.format("Waitting proxy to check query %s %s with Google on page %s", 
									keywordAddress.getKeyword(), 
									keywordAddress.getAddress(),
									i+1));
					validProxy = validProxyQueue.take();
					mainFrame.setTextAreaText(String.format("Get a valid proxy %s and checking query %s %s " +
							"with Google on page %s", 
									validProxy.getProxy(),
									keywordAddress.getKeyword(), 
									keywordAddress.getAddress(),
									i+1));
					clientExecuteProxyGoogle = new ClientExecuteProxySearchGoogleHost
							(httpclient,validProxy,keywordAddress, i*10);
					document = clientExecuteProxyGoogle.execue();
					if(document != null)
						break;
				}
			}
			if(document != null)
			{
//				LOGGER.info(document);
				documentList.add(document);
				validProxy = validProxyQueue.take();
			}
		}
		return documentList;
	}
	
	private List<SearchResultItem> transformToSearchItemList(List<Document> documentList)
	{
		List<SearchResultItem> searchResultItemList = new ArrayList<SearchResultItem>();
		int pageIndex = 0;
		for(Document document : documentList)
		{
			searchResultItemList.addAll(this.transformToSearchItemList(document, pageIndex));
			pageIndex ++;
		}
		return searchResultItemList;
	}
	
	private List<SearchResultItem> transformToSearchItemList(Document document, int pageIndex/*0-9*/)
	{
		List<SearchResultItem> searchResultItemList = new ArrayList<SearchResultItem>();
		Elements elements = document.select("li.g");
		int i = 1;
		int tenDigit = pageIndex == 0? 0: pageIndex*10;
		int myPageIndex = 0;
		for(Element liElement : elements)
		{
			myPageIndex = tenDigit + i;
			Element aaElement = document.select("a:contains(Images)").first();
			String googleAddress = getGoogleAddress(aaElement.attr("href"));
			
			Element aElement = liElement.select("a").first();
			String googleLink = aElement.attr("href");
			
			LOGGER.info("page rank: " + myPageIndex + ", google link: " + googleAddress + googleLink);
			
			SearchResultItem searchResultItem = new SearchResultItem();
			searchResultItem.setKeyword(this.keywordAddress.getKeyword());
			searchResultItem.setGoogleServer(googleAddress);
			searchResultItem.setPageRank(myPageIndex);
			searchResultItem.setGoogleLink(googleAddress + googleLink);
			searchResultItem.setRequireLink(keywordAddress.getAddress());
			searchResultItemList.add(searchResultItem);
			i++;
		}
		
		return searchResultItemList;
	}
	
	private void clickMatchedItem(List<SearchResultItem> searchResultItemList) throws Exception
	{
		for(SearchResultItem searchResultItem : searchResultItemList)
		{
			if(searchResultItem.isMatchRequireLink())
			{
				clientExecuteProxyGoogle = new ClientExecuteProxyGoTarget
						(httpclient,validProxy,searchResultItem.getGoogleLink());
				clientExecuteProxyGoogle.execue();
				
				clickerDao.insetSearchResultItem(searchResultItem);
				mainFrame.setTextAreaText(clientExecuteProxyGoogle.getValidDisplayString());
			}
		}
	}
	
	private String getGoogleAddress(String imagePath)
	{
		String result = imagePath.substring(0, imagePath.lastIndexOf("/"));
		return result;
	}
	
	public static void main(String args[]) throws URISyntaxException
	{
		URI uri = new URI(".google.com/abcde/aaa");
		LOGGER.info(uri.getScheme() + " " + uri.getHost());
	}

}
